//
//  FGXmppManager.m
//  FGChat
//
//  Created by chfg on 16/4/1.
//  Copyright © 2016年 chfg. All rights reserved.
//

#import "FGXmppManager.h"

@interface FGXmppManager ()<XMPPStreamDelegate>

/** 用来记录登录mima */
@property(nonatomic, copy)NSString *password;

@end

@implementation FGXmppManager

#pragma mark - 单例设计模式实现
static FGXmppManager *_share;
+ (instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        _share = [[FGXmppManager alloc] init];
        
    });
    
    return _share;
}


#pragma mark - 懒加载 (初始化xmppStream)
- (XMPPStream *)xmppStream
{
    if (_xmppStream == nil) {
        
        _xmppStream = [[XMPPStream alloc] init];
        
        // 设置多播代理
        [_xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(0, 0)];
        
    }
    return _xmppStream;
}

#pragma mark - 登录方法(即连接服务器)
- (void)loginWithXmppJid:(XMPPJID *)jid password:(NSString *)password
{
    // 1.设置jid
    self.xmppStream.myJID = jid;
    
    // 2.记录密码
    self.password = password;
    
    // 3.连接服务器
    NSError *error;
    [self.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error];
    
    if (error) {
        NSLog(@"连接服务器错误 -- %@",error);
    }
}


#pragma mark -- 注销
- (void)logout
{
    // 1.发送 ‘离线’消息
    XMPPPresence *offline = [XMPPPresence presenceWithType:@"unavailable"];
    
    [self.xmppStream sendElement:offline];
    
    // 2.断开连接
    [self.xmppStream disconnect];
}


#pragma mark - XMPPStreamDelegate
#pragma mark -- 1.连接服务器相关
/**
 *   连接服务器成功 ,要发送密码,进行授权
 */
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
    sender.hostName = @"127.0.0.1";
    sender.hostPort = 5222;
    
    NSLog(@"连接服务器成功!!");
    
    NSError *error;
    [self.xmppStream authenticateWithPassword:self.password error:&error];
    if (error) {
        NSLog(@"密码授权错误!! -- %@",error);
    }
}

/**
 *  连接服务器失败时调用
 */
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    NSLog(@"连接服务器失败!! -- %@",error);
}


#pragma mark -- 2.密码授权相关
/**
 *  密码授权成功 之后 设置出席状态
 */
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    NSLog(@"密码授权成功");
    
    //设置出席状态
    XMPPPresence *persence = [XMPPPresence presence];
    
    [persence addChild:[DDXMLElement elementWithName:@"show" stringValue:@"online"]];
    
    [persence addChild:[DDXMLElement elementWithName:@"status" stringValue:@"zaixian"]];
    
    [self.xmppStream sendElement:persence];
}

/**
 *  密码授权失败
 */
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error
{
    NSLog(@"密码授权失败 -- %@",error);
}






@end

